import { nextTick } from 'vue'
import axios from "axios"
import { showConfirmDialog, showToast } from "vant"
import router from "@/router/index"

// 创建 axios 实例
const service = axios.create({
  baseURL: "https://testapi.3dshome.com/",
  timeout: 60000,
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code == 200) {
      return res
    } else if (res.code == 401 || res.code == 0) {
      nextTick(() => {
        showConfirmDialog({
          title: '提示',
          message: localStorage.getItem('token') ? 'token已失效，请重新登录' : '暂未登录，请先登录',
          confirmButtonText: '重新登录',
          cancelButtonText: '游客进入',
        })
          .then(() => {
            localStorage.clear()
            sessionStorage.clear()
            setTimeout(() => {
              router.push('/login')
            }, 300)
          })
          .catch(() => {
            localStorage.clear()
            sessionStorage.clear()
            setTimeout(() => {
              router.push('/')
            }, 300)
          })
      })
      return Promise.reject(res)
    } else {
      showToast(res.msg || '请求失败')
      return Promise.reject(res)
    }
  },
  error => {
    showToast(error.message || '请求出错')
    return Promise.reject(error)
  }
)

// 封装请求方法
const request = {
  post ({ url, data = {}, headers = {} }) {
    return service({
      method: "post",
      url,
      data,
      headers,
    })
  },
  get ({ url, data = {}, headers = {} }) {
    return service({
      method: "get",
      url,
      params: data,
      headers,
    })
  },
}

// 接口封装示例
export default {
  // 登录示例
  login (data) {
    return request.post({
      url: "index.php/api/common",
      data: {
        code: "ucLogin",
        data,
      },
    })
  },
  // 退出登录
  loginOut (data) {
    return request.post({
      url: "/index.php/api/common",
      headers: {
        token: localStorage.getItem("token"),
      },
      data: {
        code: "ucLoginOut",
        data,
      },
    })
  },
  // 获取验证码
  getVerificationCode (data) {
    return request.post({
      url: "/index.php/api/common",
      data: {
        code: "competitionSignupSmsVerificationCode",
        data,
      },
    })
  },
  // 提交大赛报名表单
  submitCompetitionSignupForm (data) {
    return request.post({
      url: "/index.php/api/common",
      data: {
        code: "competitionSignupAdd",
        data,
      },
    })
  },
  // 上传图片
  uploadImage (data) {
    return request.post({
      url: "/index.php/api/common",
      data: {
        code: "adminUpload",
        data,
      },
    })
  },
}
